package com.yyoa.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.yyoa.entity.User;
import com.yyoa.service.UserService;
import com.yyoa.util.CookieUtil;

public class AuthorizedInterceptor implements HandlerInterceptor {

	private UserService userService;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();
		// 登陆请求不拦截
		if (uri.indexOf("login") != -1) {
			return true;
		}

		// 设置不拦截的对象
		String[] noFilters = new String[] { "login", "exception" }; // 对登录本身的页面以及业务不拦截
		for (String s : noFilters) {
			if (uri.indexOf(s) != -1) {
				return true;
			}
		}

		// 除了不拦截的对象以外
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
				+ "/";

		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		if (u == null) {
			// 未登录
			response.sendRedirect(basePath + "pc/page/login/index.html");
			return false;
		}

		// 已经登录，判断他是否登录前勾选了记住密码
		Cookie cokLoginName = CookieUtil.getCookieByName(request, "loginName");
		Cookie cokLoginPwd = CookieUtil.getCookieByName(request, "loginPwd");
		if (cokLoginName != null && cokLoginPwd != null && cokLoginName.getValue() != null
				&& cokLoginPwd.getValue() != null) {
			String loginName = cokLoginName.getValue();
			String loginPwd = cokLoginPwd.getValue();
			// 检查到客户端保存了用户的密码，进行该账户的验证
			User users = userService.login(loginName, loginPwd);
			if (users == null) {
				CookieUtil.addCookie(response, "loginName", null, 0); // 清除Cookie
				CookieUtil.addCookie(response, "loginPwd", null, 0); // 清除Cookie
				CookieUtil.addCookie(response, "role", null, 0); // 清除Cookie
				CookieUtil.addCookie(response, "loginRememberPwd", null, 0); // 清除Cookie
				session.setAttribute("errorInfo", "请登录！");
				response.sendRedirect(basePath + "pc/page/login/index.html");
			}
			// 如果账户验证成功，则跳转到点击的页面
			session.setAttribute("user", users);
		}

		return true;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
